import axios from "axios";
import Element from "element-ui"
import {refreshToken} from "../api/blog";
import router from "../router";

let isRefreshing = false
let requests = []

axios.interceptors.request.use(config => {
    console.log(sessionStorage.getItem("token"))
    config.headers.Authorization = sessionStorage.getItem("token")
    return config
})

axios.interceptors.response.use(response => {
    let res = response.data;

    console.log("=================")
    console.log(response)
    console.log("=================")

    if (res.code === 200) {
        return response
    } else {
        return Promise.reject(response.data.msg)
    }
},error => {
    if (!isRefreshing){
        isRefreshing = true
        if (error.response.status === 401){
            console.log("===================1111111111=========")
            refreshToken(sessionStorage.getItem("token"),sessionStorage.getItem("access_token")).then(res=>{

                console.log(res)
                sessionStorage.removeItem("token")
                sessionStorage.removeItem("access_token")
                sessionStorage.setItem("token",res.data.data.token)
                sessionStorage.setItem("access_token",res.data.data.access_token)
                error.config.headers.Authorization = sessionStorage.getItem("token")
                return axios.request(error.config)
            })

        }
        isRefreshing = false
        requests = []
    }


    return Promise.reject(error)
})
